package jh.com.jhappbf.contract;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.ContractModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.MoneyNumToChinese;
import jh.com.jhappbf.weight.query.SelectActivity;

public class ContractAdd extends AbActivity implements OnClickListener {

    private EditText mTxtAccount;
    private EditText mTxtPhone;
    private EditText mTxtUnit;
    private EditText mTxtCargoname;
    private EditText mTxtSpec;
    private EditText mTxtSender;
    private EditText mTxtReceiver;
    private EditText mTxtAmount;
    private EditText mTxtCredit;
    private EditText mTxtTypes;
    private EditText mTxtPrice;
    private EditText mTxtMoney;
    private EditText mTxtMoneyRMB;
    private EditText mTxtPanId;
    private EditText mTxtSalePerson;
    private EditText mTxtChargePerson;
    private EditText mTxtAddPerson;

    private ImageView mAccountImg;

    private Context mAppcontext;
    private AbTitleBar mTitleBar;
    private final int GETRECEIVER = 0X0001;
    private final int REQUERY_CONTACT = 0x0002;// 访问通讯录
    private final int GETCARGONAME = 0X0003;
    private final int GETSPEC = 0X0004;
    private final int GETSENDER = 0x0005;
    private final int GETUNIT = 0X0006;
    private final int GETTYPES = 0X0007;
    private String mPlanId = "";
    private String mFlag = "add";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            mAppcontext = getApplicationContext();
            setAbContentView(R.layout.contract_add_activity);
            mTitleBar = this.getTitleBar();
            mTitleBar.setTitleText("信用额度修改");
            mTitleBar.setLogo(R.drawable.button_selector_back);
            mTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
            ;
            mTitleBar.setTitleTextMargin(10, 0, 0, 0);
            mTitleBar.setLogoLine(R.mipmap.line);
            initView();
        } catch (Exception e) {
            e.getMessage();
        }

    }

    /**
     * 生成计划单Id
     */
    private void initPlanId() {
        String id = getPlanId();
        mTxtPanId.setText(id);
    }

    /**
     * 初始化
     */
    private void initView() {
        mTxtAccount = findViewById(R.id.contract_account_txt);
        mTxtPhone = findViewById(R.id.contract_phone_txt);
        mTxtUnit = findViewById(R.id.contract_unit_txt);
        mTxtCargoname = findViewById(R.id.contract_cargoname_txt);
        mTxtSpec = findViewById(R.id.contract_spec_txt);
        mTxtSender = findViewById(R.id.contract_sender_txt);
        mTxtReceiver = findViewById(R.id.contract_receiver_txt);
        mTxtAmount = findViewById(R.id.contract_amount_txt);
        mTxtCredit = findViewById(R.id.contract_creditAmount_txt);
        mTxtTypes = findViewById(R.id.contract_types_txt);
        mTxtMoney = findViewById(R.id.contract_money_txt);
        mTxtPrice = findViewById(R.id.contract_price_txt);
        mTxtMoneyRMB = findViewById(R.id.contract_money_rmb_txt);
        mTxtPanId = findViewById(R.id.contract_id_txt);
        mTxtSalePerson = findViewById(R.id.contract_sale_person_txt);
        mTxtChargePerson = findViewById(R.id.contract_charge_person_txt);
        mTxtAddPerson = findViewById(R.id.contract_add_person_txt);

        /*
         * mAccouantImg = (ImageView) findViewById(R.id.contract_account_img);
         * mAccouantImg.setOnClickListener(this);
         */
        ImageView mPhoneImg = findViewById(R.id.contract_phone_img);
        mPhoneImg.setOnClickListener(this);
        ImageView mUnitImg = findViewById(R.id.contract_unit_img);
        mUnitImg.setOnClickListener(this);
        ImageView mCargonameImg = findViewById(R.id.contract_cargoname_img);
        mCargonameImg.setOnClickListener(this);
        ImageView mSpecImg = findViewById(R.id.contract_spec_img);
        mSpecImg.setOnClickListener(this);
        ImageView mSenderImg = findViewById(R.id.contract_sender_img);
        mSenderImg.setOnClickListener(this);
        ImageView mReceiverImg = findViewById(R.id.contract_receiver_img);
        mReceiverImg.setOnClickListener(this);
        ImageView mTypesImg = findViewById(R.id.contract_types_img);
        mTypesImg.setOnClickListener(this);

        View rightView = View.inflate(this, R.layout.title_right_ok_btn_view, null);
        mTitleBar.addRightView(rightView);
        Button mBtnOk = rightView.findViewById(R.id.title_right_ok_btn);
        mBtnOk.setOnClickListener(this);

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String money = mTxtMoney.getText().toString();
                try {
                    String valString = MoneyNumToChinese.arabNumToChineseRMB(money);
                    mTxtMoneyRMB.setText(valString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        mTxtMoney.addTextChangedListener(watcher);
        getPlan();
    }

    /**
     * 修改计划需要调出计划
     */
    private void getPlan() {
        Intent intent = getIntent();
        mFlag = intent.getStringExtra("flag");
        if ("add".equals(mFlag)) {
            mTitleBar.setTitleText("添加计划");
            initPlanId();
            mTxtAddPerson.setText(State.mName);
        } else {
            mTitleBar.setTitleText("修改信用额度");
            initUpdatePlan();
        }

        TextWatcher watcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getPlanAmount();
            }
        };
        mTxtMoney.addTextChangedListener(watcher);
        mTxtPrice.addTextChangedListener(watcher);
    }

    ///获取计划量
    private void getPlanAmount() {
        String money = mTxtMoney.getText().toString();
        String price = mTxtPrice.getText().toString();
        if ("".equals(money) || "".equals(price) || "0".equals(price)) {
            mTxtAmount.setText("");
            return;
        }
        NumberFormat nfFormat = NumberFormat.getNumberInstance();
        nfFormat.setMaximumFractionDigits(3);
        nfFormat.setRoundingMode(RoundingMode.DOWN);
        nfFormat.setGroupingUsed(false);
        double dMoney = Double.parseDouble(money);
        double dPrice = Double.parseDouble(price);
        String plan = nfFormat.format(dMoney / dPrice);
        mTxtAmount.setText(plan);
    }

    /**
     * 获取计划
     */
    private void initUpdatePlan() {
        Intent intent = getIntent();
        ContractModel model = intent.getParcelableExtra("data");
        if (model != null) {
            mTxtAccount.setText(model.getAccount());
            mTxtPhone.setText(model.getPhone());
            mTxtTypes.setText(model.getTypes());
            mTxtCargoname.setText(model.getCargoname());
            mTxtSpec.setText(model.getSepc());
            mTxtSender.setText(model.getSender());
            mTxtReceiver.setText(model.getReceiver());
            mTxtUnit.setText(model.getUnit());
            mTxtAmount.setText(model.getAmount());
            mTxtCredit.setText(model.getCredit());
            mPlanId = model.getPlanId();
            mTxtMoney.setText(model.getMoney());
            mTxtPrice.setText(model.getPrice());
            mTxtPanId.setText(model.getPlanId());
            mTxtMoneyRMB.setText(model.getMemo());
            mTxtSalePerson.setText(model.getSalePerson());
            mTxtAddPerson.setText(State.mName);
            mTxtAmount.setEnabled(false);
            mTxtMoney.setEnabled(false);
            mTxtPrice.setEnabled(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String value = data.getStringExtra("result");
            if (requestCode == GETRECEIVER) {
                mTxtReceiver.setText(value);
            } else if (requestCode == REQUERY_CONTACT) {
                Uri contactUri = data.getData();
                String[] fields = new String[]{ContactsContract.Contacts._ID};
                Cursor cursor = null;
                if (contactUri != null) {
                    cursor = getContentResolver().query(contactUri, fields,
                            null, null, null);
                }
                if (cursor != null && cursor.getCount() == 0) {
                    cursor.close();
                    return;
                }
                if (cursor != null) {
                    cursor.moveToFirst();
                }
                String id = null;
                if (cursor != null) {
                    id = cursor.getString(0);
                }
                Cursor phones = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                                + id, null, null);
                if (phones != null && phones.getCount() == 0) {
                    return;
                }
                if (phones != null) {
                    phones.moveToFirst();
                }
                String phoneNumber = null;
                if (phones != null) {
                    phoneNumber = phones
                            .getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                mTxtPhone.setText(phoneNumber);
                if (phones != null) {
                    phones.close();
                }
                if (cursor != null) {
                    cursor.close();
                }
            } else if (requestCode == GETUNIT) {
                mTxtUnit.setText(value);
            } else if (requestCode == GETCARGONAME) {
                mTxtCargoname.setText(value);
            } else if (requestCode == GETSPEC) {
                mTxtSpec.setText(value);
            } else if (requestCode == GETSENDER) {
                mTxtSender.setText(value);
            } else if (requestCode == GETTYPES) {
                mTxtTypes.setText(value);
            }
        }
    }

    /**
     * 第一次加载
     */
    private void operatorServer(final String receiver, final String money) {
        AbLoadDialogFragment mDialogFragment = AbDialogUtil.showLoadDialog(ContractAdd.this,
                R.mipmap.ic_load, "操作中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            if ("add".equals(mFlag)) {
                addContract(money, receiver);
            } else {
                updatePlan();
            }

        });
    }

    /**
     * 添加计划
     */
    private void addContract(String amount, String receiver) {

        if (isEmpty(mTxtPanId, "计划单号")) {
            return;
        }
        if (isEmpty(mTxtReceiver, "收货")) {
            return;
        }
        if (isEmpty(mTxtMoney, "金额")) {
            return;
        }

        String methodName = "AddPlan";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("planId");
        param.add("receiver");
        param.add("sender");
        param.add("types");
        param.add("money");
        param.add("rmb");
        param.add("name");
        param.add("salePerson");
        param.add("chargePerson");

        value.add(mTxtPanId.getText().toString());
        value.add(mTxtReceiver.getText().toString());
        value.add(mTxtSender.getText().toString());
        value.add(mTxtTypes.getText().toString());
        value.add(mTxtMoney.getText().toString());
        value.add(mTxtMoneyRMB.getText().toString());
        value.add(State.mName);
        value.add(mTxtSalePerson.getText().toString());
        value.add(mTxtChargePerson.getText().toString());

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractAdd.this);
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    ContractAdd.this.setResult(RESULT_OK);
                    Toast.makeText(ContractAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                    refresh();
//						ContractAdd.this.finish();
                } else {
                    Toast.makeText(ContractAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(ContractAdd.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractAdd.this);
            Toast.makeText(ContractAdd.this, "操作失败,请重试", Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 获取计划单位Id
     */
    private String getPlanId() {
        DecimalFormat dFormat = new DecimalFormat("000");
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        String date = timeFormat.format(calendar.getTime());
        String planId = State.mApplicationCode + dFormat.format(Integer.parseInt(State.mUserId)) + date;
        return planId;
    }

    /**
     * 刷新
     */
    private void refresh() {
        initPlanId();
        mTxtMoney.setText("");
        mTxtSender.setText("");
        mTxtReceiver.setText("");
        mTxtSalePerson.setText("");
        mTxtChargePerson.setText("");
        mTxtTypes.setText("");
        mTxtAddPerson.setText(State.mName);
    }

    /**
     * 判断输入是否为空
     *
     * @param txt  文本框
     * @param tips 提示内容
     * @return 为空返回ture 否则返回false
     */
    private boolean isEmpty(EditText txt, String tips) {
        String content = txt.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(ContractAdd.this, tips + "不允许为空!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return false;
    }

    /**
     * 更新计划
     */
    private void updatePlan() {
        String methodName = "updatePlan";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("planId");
        param.add("receiver");
        param.add("sender");
        param.add("money");
        param.add("rmb");
        param.add("types");
        param.add("salePerson");
        param.add("chargePeople");
        param.add("addPerson");
        param.add("updateContent");
        param.add("xinyongedu");
        String updateContent = getUpdateContent();
        value.add(mPlanId);
        value.add(mTxtReceiver.getText().toString());
        value.add(mTxtSender.getText().toString());
        value.add(mTxtMoney.getText().toString());
        value.add(mTxtMoneyRMB.getText().toString());
        value.add(mTxtTypes.getText().toString());
        value.add(mTxtSalePerson.getText().toString());
        value.add(mTxtChargePerson.getText().toString());
        value.add(State.mName);
        value.add(updateContent);
        value.add(mTxtCredit.getText().toString());
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractAdd.this);
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    ContractAdd.this.setResult(RESULT_OK);
                    Toast.makeText(ContractAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                    ContractAdd.this.finish();
                } else {
                    Toast.makeText(ContractAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(ContractAdd.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractAdd.this);
            Toast.makeText(ContractAdd.this, "操作失败,请重试", Toast.LENGTH_SHORT)
                    .show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 获取要修改的内容
     */
    private String getUpdateContent() {
        ContractModel model = getIntent().getParcelableExtra("data");
        if (model != null) {
            StringBuilder updateBuilder = new StringBuilder("修改:");
            if (!mTxtPhone.getText().toString().equals(model.getPhone())) {
                updateBuilder.append("联系电话由").append(model.getPhone()).append("改为").append(mTxtPhone.getText());
            }
            if (!mTxtAccount.getText().toString().equals(model.getAccount())) {
                updateBuilder.append("账号由").append(model.getAccount()).append("改为").append(mTxtAccount.getText());
            }
            if (!mTxtTypes.getText().toString().equals(model.getTypes())) {
                updateBuilder.append("类型由").append(model.getTypes()).append("改为").append(mTxtTypes.getText());
            }
            if (!mTxtCargoname.getText().toString().equals(model.getCargoname())) {
                updateBuilder.append("货名由").append(model.getCargoname()).append("改为").append(mTxtCargoname.getText());
            }
            if (!mTxtSpec.getText().toString().equals(model.getSepc())) {
                updateBuilder.append("规格由").append(model.getSepc()).append("改为").append(mTxtSpec.getText());
            }
            if (!mTxtSender.getText().toString().equals(model.getSender())) {
                updateBuilder.append("发货由").append(model.getSender()).append("改为").append(mTxtSender.getText());
            }
            if (!mTxtReceiver.getText().toString().equals(model.getReceiver())) {
                updateBuilder.append("收货由").append(model.getReceiver()).append("改为").append(mTxtReceiver.getText());
            }
            if (!mTxtUnit.getText().toString().equals(model.getUnit())) {
                updateBuilder.append("单位由").append(model.getUnit()).append("改为").append(mTxtUnit.getText());
            }

            if (!mTxtCredit.getText().toString().equals(model.getCredit())) {
                updateBuilder.append("信用额").append(model.getCredit()).append("改为").append(mTxtCredit.getText());
            }

            return updateBuilder.toString();
        } else {
            return "";
        }

    }

    @Override
    public void onClick(View v) {
        Intent i;
        switch (v.getId()) {
            case R.id.contract_phone_img:
                getPhoneFromAddressBook();
                break;
            case R.id.contract_unit_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "receiver");
                startActivityForResult(i, GETUNIT);
                break;
            case R.id.contract_cargoname_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "cargoname1");
                startActivityForResult(i, GETCARGONAME);
                break;
            case R.id.contract_spec_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "spec");
                startActivityForResult(i, GETSPEC);
                break;
            case R.id.contract_receiver_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "receiver");
                startActivityForResult(i, GETRECEIVER);
                break;
            case R.id.contract_sender_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "sender");
                startActivityForResult(i, GETSENDER);
                break;
            case R.id.contract_types_img:
                i = new Intent(ContractAdd.this, SelectActivity.class);
                i.putExtra("flag", "type");
                startActivityForResult(i, GETTYPES);
                break;
            case R.id.title_right_ok_btn:
                saveData();
            default:
                break;
        }
    }

    // 获取电话号码从通讯录中
    private void getPhoneFromAddressBook() {
        Intent i = new Intent(Intent.ACTION_PICK,
                ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(i, REQUERY_CONTACT);
    }

    /**
     * 保存称重数据
     */
    private void saveData() {
        String receiver = mTxtReceiver.getText().toString();
        String money = mTxtMoney.getText().toString();
        String creditMoney = mTxtCredit.getText().toString();
        String id = mTxtPanId.getText().toString();
        if (TextUtils.isEmpty(creditMoney)) {
            Toast.makeText(ContractAdd.this, "信用额度不能为空!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

//        if (TextUtils.isEmpty(receiver)) {
//            Toast.makeText(ContractAdd.this, "收货单位不能为空!",
//                    Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (TextUtils.isEmpty(money)) {
//            Toast.makeText(ContractAdd.this, "计划金额不能为空!",
//                    Toast.LENGTH_SHORT).show();
//            return;
//        }

        if (!ExpressionUtils.isNumber(creditMoney)) {
            Toast.makeText(ContractAdd.this, "金额不合法!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

//		if(!ExpressionUtils.isNumber(creditMoeny))
//		{
//			mTxtCredit.setText("0");
//			return;
//		}

        operatorServer(receiver, money);
    }

}
